package com.xinghen.core.exception.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author xinghen
 * @ClassName: RmsResponseErrorHandler
 * @Package: com.xinghen.core.exception.handler
 * @Description RmsResponseErrorHandler
 * @create 2017-12-07 15:43
 */
@Slf4j
public class RmsResponseErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        // 获得错误信息
        String responseBody = getData(response.getBody());
        HttpStatus status = getHttpStatusCode(response);
        switch (status.series()) {
            case CLIENT_ERROR:
                throw new HttpClientErrorException(status, response.getStatusText(), response.getHeaders(),
                        responseBody.getBytes("UTF-8"), getCharset(response));
            case SERVER_ERROR:
                throw new HttpServerErrorException(status, response.getStatusText(), response.getHeaders(),
                        responseBody.getBytes("UTF-8"), getCharset(response));
            default:
                throw new RestClientException("Unknown status code [" + status + "]");
        }
    }

    /**
     * 读取返回的信息
     *
     * @param inputStream
     * @return
     */
    private String getData(InputStream inputStream) throws IOException {
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                log.error("getData", e);
            }
        }
        return builder.toString();
    }
}
